async function search(keywords) {
  if (!keywords) {
    return
  }
  $(function () {
    $('#main').load('./pages/search.html', function () {
      $('.se_input')[0].value = keywords
      $('.search_ct')[0].innerText = keywords
      if (bannertimer) {
        clearInterval(bannertimer)
        bannertimer = null
      }
    })
  })
  //type 1: 单曲, 10: 专辑, 100: 歌手, 1000: 歌单, 1002: 用户, 1004: MV, 1006: 歌词, 1009: 电台, 1014: 视频,
  const res = await axios({
    url: `/cloudsearch?keywords=${keywords}&type=1`,
    method: 'get',
  })
  totalNum = res.data.result.songCount; //总数
  localStorage.setItem('totalNum',totalNum)
  $('.songCount').html(totalNum); //查询的数量
  songlist = res.data.result.songs;
  // sessionStorage.setItem('total', res.data.result.songCount); //设置数据总数
  // $('.songCount')[0].innerText=res.data.result.songCount;
  songlist.forEach((item, index) => {
    $('#se_list')[0].innerHTML += `
        <tr class="se_video fx_sb">
            <td class="fx_fs fx_3">
                <div class="play_icon" onclick="play_v(${item.id},${item.fee},${index})"></div>
                <span>${item.name}</span>
            </td>
            <td class="se_actions fx_1 fx_sa">
                <section class="se_action fx_sa">
                    <div class="action_add"></div>
                    <div class="action_sc"></div>
                    <div class="action_share"></div>
                    <div class="action_download"></div>
                </section>
            </td>
            <td class=" fx_1">
                ${item.ar[0].name}
            </td>
            <td class=" fx_1"><span>《${item.al.name}》</span></td>
            <td class="toMinutes fx_1"><span>${toMinutes(item.dt)}</span></td>
        </tr>
        `
    localStorage.setItem('typeID',1)
    cre_Page(1, 0)

  })
}


//分页按钮
async function cre_Page(val, index) {
  $('.pagination-sm').html('')
  var total= localStorage.getItem('totalNum')
  for (let i = 1; i <= Math.ceil(total / 30); i++) {
    $('.pagination-sm')[0].innerHTML += `<li class="page-item cp"><sapn class="page-link" href="javascript:;" onclick="changePage(${i})">${i}</sapn></li>
  `
  }
  $('.pagination-sm li').eq(index).addClass('active')
}

//分页
async function changePage(index) {
  $('.pagination-sm').children().removeClass('active');
  let type = localStorage.getItem('typeID')
  se_search(type, (index - 1) * 30)
  $('.pagination-sm li').eq(index - 1).addClass('active')
}

// 数字大于1万以万为单位
function toWan(val) {
  return val >= 10000 ? (Math.floor(val / 10000) + '万') : val
}

// 秒化分钟
function toMinutes(val) {
  return (new Date(val).getMinutes() >= 10 ? new Date(val).getMinutes() : '0' + new Date(val).getMinutes()) +
    ':' + (new Date(val).getSeconds() >= 10 ? new Date(val).getSeconds() : '0' + new Date(val).getSeconds())
}


//歌单播放事件
async function play_playlist(id) {
  res = await axios({
    url: `/playlist/detail?id=${id}`,
    method: 'get'
  })
  let playlist = res.data.playlist.tracks;
  // 默认播放歌单第一首歌
  play_video(playlist[0].id)
}

function play_v(val, isVip,index) {
  if (isVip == 1) {
    alert(`本歌曲为VIP歌曲，请开通VIP后再播放！`)
    return
  }
  play_video(val)
  $('.play_icon').removeClass('play_icon_cl')
  $('.play_icon').eq(index).addClass('play_icon_cl')
}
//判断字符串是否包含字母
function hasLetter(str) {
  for (var i in str) {
    var asc = str.charCodeAt(i);
    if ((asc >= 65 && asc <= 90 || asc >= 97 && asc <= 122)) {
      return true;
    }
  }
  return false;
}
/**
 * 
 * @param {vid}  视频vid
 */
//播放视频 MV
async function play_mv(vid = 5436712) {
  $('#main').load('./pages/mv.html', function () {
    list_Detail(vid) //获取mv视频
    async function list_Detail(vid) {
      if (hasLetter(vid)) {
        const res = await axios({
          url: `/video/url?id=${vid}`,
          method: 'get'
        })
        $('#MV').prop("src", res.data.urls[0].url)

        //相关视频推荐
        getMv_allvideo(vid)
        async function getMv_allvideo(vid) {
          const res = await axios({
            url: `related/allvideo?id=${vid}`,
            method: 'get'
          })
          let result = res.data.data
          result.forEach((item, index) => {
            $('.allvideo')[0].innerHTML += `
            <dl class="mv_r_dl fx_sb" onclick="play_mv('${item.vid}')">
                  <dt class="mv_r_dt">
                      <img src="${item.coverUrl}?param=96y54" alt="" srcset="">
                      <div class="play_num"><span class="play_icon"></span>${toMinutes(item.durationms)}</div>
                  </dt>
                  <dd class="mv_r_dd f-thide">
                      <div class="f14">${item.title}</div>
                      <div class="c_666">${toWan(item.playTime)}</div>
                      <div class="c_666">${item.type==1?'by':''} ${item.creator[0].userName} ${(item.creator[1])?item.creator[0].userName:''}</div>
                  </dd>
              </dl>
            `
          })
        }
        // 获取mv视频数据
        getMv_data(vid)
        async function getMv_data(vid) {
          const res = await axios({
            url: `/video/detail?id=${vid}`,
            method: 'get'
          })
          let result = res.data.data
          $('.mv_title').html(result.title); //标题
          $('.subCount a').html(result.subscribeCount); //收藏数
          $('.shareCount a').html(result.shareCount); //分享数
          $('.dz').html('(' + result.praisedCount + ')'); //点赞数
          $('.publishTime').html(new Date(result.publishTime).toLocaleDateString()); //发行时间
          $('.playCount').html(toWan(result.playTime)); //播放次数
          $('.mv_er a').html(result.creator.nickname); //作者
        }

      } else {
        const res = await axios({
          url: `/mv/url?id=${vid}`,
          method: 'get'
        })
        $('#MV').prop("src", res.data.data.url)
        // 获取mv视频数据
        getMv_data(vid)
        async function getMv_data(vid) {
          const res = await axios({
            url: `/mv/detail?mvid=${vid}`,
            method: 'get'
          })
          let result = res.data.data
          $('.mv_title').html(result.name); //标题
          $('.subCount a').html(result.subCount); //收藏数
          $('.shareCount a').html(result.shareCount); //分享数
          $('.publishTime').html(result.publishTime); //发行时间
          $('.playCount').html(toWan(result.playCount)); //播放次数
          $('.mv_er a').html(result.artists[0].name); //作者
          $('.mv_btn>div').eq(0).remove()
        }
        // /mv/detail?mvid=

        //相关视频推荐
        getMv_allvideo(vid)
        async function getMv_allvideo(vid) {
          const res = await axios({
            url: `/simi/mv?mvid=${vid}`,
            method: 'get'
          })
          let result = res.data.mvs
          result.forEach((item, index) => {
            $('.allvideo')[0].innerHTML += `
         <dl class="mv_r_dl fx_sb" onclick="play_mv(${item.id})">
              <dt class="mv_r_dt">
                  <img src="${item.cover}?param=96y54" alt="" srcset="">
                  <div class="play_num"><span class="play_icon"></span>${toMinutes(item.duration)}</div>
              </dt>
              <dd class="mv_r_dd f-thide">
                  <div class="f14">${item.name}</div>
                  <div class="c_666">${toWan(item.playCount)}</div>
                  <div class="c_666">${item.type==1?'by':''} ${item.artists[0].name} ${(item.artists[1])?item.artists[0].name:''}</div>
              </dd>
          </dl>
         `
          })
        }
      }

    }
  })
}


// 主播电台
function goToDjradioDetail(id){
  sessionStorage.setItem('djId',id)
  $('#main').load('./pages/djradioDetail.html', function () {
        
  })
}
